/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.fjs.liyq.web;

import edu.fjs.liyq.entity.Product;
import edu.fjs.liyq.service.ProductService;
import edu.fjs.liyq.service.impl.ProductServiceImpl;
import edu.fjs.liyq.util.Pager;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author danny
 */
public class ProductServlet extends HttpServlet {

    private static final String TMP_DIR_PATH = "d:\\tmp";
    private File tmpDir;
    private static final String DESTINATION_DIR_PATH = "/files";
    private File destinationDir;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config); //To change body of generated methods, choose Tools | Templates.
        tmpDir = new File(TMP_DIR_PATH);
        if (!tmpDir.isDirectory()) {
            throw new ServletException(TMP_DIR_PATH + " is not a directory");
        }
        String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
        destinationDir = new File(realPath);
        destinationDir.mkdirs();
        if (!destinationDir.isDirectory()) {
            throw new ServletException(DESTINATION_DIR_PATH
                    + " is not a directory");
        }
    }

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        /*
        multipart请求无法用request.getParameter（）获取action值
        我们使用request.getHeader("Content-Type")判断是否为multipart请求，再做后续处理
        */
        String contentType = request.getHeader("Content-Type");
        if (contentType != null && contentType.contains("multipart/form-data")) {
            doAdd(request, response);
        } else {
            // 根据action进行不同的页面逻辑处理
            String action = request.getParameter("action");
            if ("list".equals(action)) {
                doListProducts(request, response);
            } else if ("addForm".equals(action)) {
                request.getRequestDispatcher("/WEB-INF/jsp/productAdd.jsp").forward(request, response);
            } else if ("doAdd".equals(action)) {

            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private void doListProducts(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 从前端获取页面初始化参数
        int page = 1;
        int row = 5;
        String strPage = request.getParameter("page"); // 当前页码数
        try {
            page = Integer.valueOf(strPage);
        } catch (Exception e) {
            log(e.getMessage(), e);
        }
        String strRow = request.getParameter("row");  // 每页显示数据条数
        try {
            row = Integer.valueOf(strRow);
        } catch (Exception e) {
            log(e.getMessage(), e);
        }
        Pager pager = new Pager(0, row, page);

        // 读取数据
        ProductService service = new ProductServiceImpl();
        List<Product> pl = service.getProductListWithPage(pager.getCurrentPage(), pager.getRowPerPage());
        int count = service.getProductCount();
        pager.setRowCount(count);
        // 将模型数据放到request范围
        request.setAttribute("resultList", pl);
        request.setAttribute("pager", pager);
        // 请求转发
        request.getRequestDispatcher("/WEB-INF/jsp/productList.jsp").forward(request, response);
    }

    private void doAdd(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        Map<String, String> params = new HashMap<String, String>();
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
        fileItemFactory.setRepository(tmpDir);
        String fileName = null;

        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
        uploadHandler.setHeaderEncoding("utf-8");
        try {
            List items = uploadHandler.parseRequest(request);
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                if (item.isFormField()) {
                    params.put(item.getFieldName(), item.getString("utf-8"));
                } else {
                    if (item.getSize() > 0) {
//                        fileName = Long.toString(id)
//                                + item.getName().substring(
//                                        item.getName().lastIndexOf("."));
                        fileName = System.currentTimeMillis() + item.getName().substring(item.getName().lastIndexOf("."));
                        File file = new File(destinationDir, fileName);
                        item.write(file);
                    }
                }
            }
        } catch (FileUploadException ex) {
            ex.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        // 获取请求参数并封装对象
        Product product = new Product();
//        try {
//            product.setEpName(request.getParameter("epName"));
//            product.setEpDescription(request.getParameter("epDescription"));
//            product.setEpPrice(Double.valueOf(request.getParameter("epPrice")));
//            product.setEpStock(Integer.valueOf(request.getParameter("epStock")));
//            product.setEpFileName(request.getParameter("epFileName"));
//        } catch (NumberFormatException e) {
//            log(e.getMessage(), e);
//        }
        try {
             product.setEpName(params.get("epName"));
            product.setEpDescription(params.get("epDescription"));
            product.setEpPrice(Double.valueOf(params.get("epPrice")));
            product.setEpStock(Integer.valueOf(params.get("epStock")));
            product.setEpFileName(fileName);
        } catch (NumberFormatException e) {
            log(e.getMessage(), e);
        }

        // 调用service添加对象
        ProductService service = new ProductServiceImpl();
        boolean result = false;
        try {
            result = service.addProduct(product);
        } catch (Exception e) {
            log(e.getMessage(), e);
        }

        // 根据模型返回结果处理页面逻辑
        if (result) {
            response.sendRedirect(request.getContextPath() + "/product.html?action=list");
        } else {
            request.setAttribute("error", "添加失败，请重试！");
            request.getRequestDispatcher("/WEB-INF/jsp/productAdd.jsp").forward(request, response);
        }
    }

}
